package routers

import (
	"fmt"
	"gin-demo/internal/config"
	"gin-demo/pkg/logger"
	"net/http"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

type album struct {
	ID     string  `json:"id"`
	Title  string  `json:"title"`
	Artist string  `json:"artist"`
	Price  float64 `json:"price"`
}

var albums = []album{
	{ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99},
	{ID: "2", Title: "Jeru", Artist: "Gerry Mulligan", Price: 17.99},
	{ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99},
}

func getAlbums(c *gin.Context) {
	c.IndentedJSON(http.StatusOK, albums)
}
func getAlbum(c *gin.Context) {
	id := c.Param("id")
	if id == "a" {
		panic("Error: Invalid ID1")
	}
	for _, album := range albums {
		if album.ID == id {
			c.IndentedJSON(http.StatusOK, album)
			return
		}
	}
}

func getDb(c *gin.Context) {
	cfg, err := config.LoadConfig()
	if err != nil {
		fmt.Printf("Failed to load config: %v\n", err)
		return
	}
	c.IndentedJSON(http.StatusOK, cfg.Database)
}

// SetupRoutes 设置路由
func SetupRoutes(r *gin.Engine, logger *logger.LoggerUtil) {
	// 自定义 Gin 日志中间件
	r.Use(func(c *gin.Context) {
		// 记录请求开始时间
		start := c.Request.URL.Path

		// 处理请求
		c.Next()

		// 从上下文中获取 loggerUtil 实例
		logger := logger.GetLoggerFromContext(c)
		if logger != nil {
			logger.Info("Request",
				zap.String("method", c.Request.Method),
				zap.String("path", start),
				zap.Int("status", c.Writer.Status()),
			)
		}
	})

	// 定义路由
	r.GET("/", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "welcome my page",
		})
		// 从上下文中获取 loggerUtil 实例
		logger := logger.GetLoggerFromContext(c)
		if logger != nil {
			logger.Info("Route accessed1", zap.String("path", c.Request.URL.Path))
		}
	})
	r.GET("/albums", getAlbums)
	r.GET("/albums/:id", getAlbum)
	r.GET("/db", getDb)
}
